package com.chen.nongansampling;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.azhon.appupdate.dialog.NumberProgressBar;
import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.chen.nongansampling.activity.NoticeActivity;
import com.chen.nongansampling.activity.SampleActivity;
import com.chen.nongansampling.activity.SettingActivity;
import com.chen.nongansampling.app.BaseApplication;
import com.chen.nongansampling.bean.SimpleRequest;
import com.chen.nongansampling.bean.TodayResponseBean;
import com.chen.nongansampling.bean.UpdateJsonBean;
import com.chen.nongansampling.bean.chucuncaiyang;
import com.chen.nongansampling.fragment.BusinessArchivesActivity;
import com.chen.nongansampling.fragment.LabelPrintedFragment;
import com.chen.nongansampling.fragment.RiskMonitorActivity;
import com.chen.nongansampling.fragment.getOperatingByPkIdFragment;
import com.chen.nongansampling.presenter.MainTablePresenter;
import com.chen.nongansampling.presenterView.MainTableView;
import com.haoyd.printerlib.manager.GPPrinterManager;
import com.king.app.dialog.AppDialog;
import com.king.app.dialog.AppDialogConfig;
import com.king.app.updater.AppUpdater;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, MainTableView, OnDownloadListener,View.OnClickListener, OnButtonClickListener {


    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.user_department)
    TextView userDepartment;
    private GridView gview;
    private List<Map<String, Object>> data_list;
    private DownloadManager manager;
    private String apkjieshao;
    private SimpleAdapter sim_adapter;
    private NumberProgressBar progressBar;
    public static Context gpngyongcontext;
    public static chucuncaiyang cunchu=new chucuncaiyang();
    @BindView(R.id.user_icon)
    ImageView userSetting;
    // 图片封装为一个数组
    private int[] icon = {R.mipmap.main_sample_mission, R.mipmap.main_sample_doc, R.mipmap.main_sample_setting, R.mipmap.main_sample_anno, R.mipmap.main_sample_risk};
    private String[] iconName = {"采样任务", "经营户档案", "设置", "通知公告", "风险监测"};
    private MainTablePresenter marketPresenter = new MainTablePresenter();
    private String url = "http://www.xindaon.cn/APPUpdate/version-info.json";
    public static boolean yx=true;
    public static int num;
    @BindView(R.id.samplingCount)
    TextView samplingCount;


    @BindView(R.id.detectionCount)
    TextView detectionCount;

    @BindView(R.id.banben)
    TextView banben;
    @BindView(R.id.trueDetectionCount)
    TextView trueDetectionCount;
    public static String apkUrl;
    public static  int Version;
    public static  Context labelcontext;
    public  UpdateJsonBean listNews;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getOperatingByPkIdFragment getOperatingByPkIdFragment = new getOperatingByPkIdFragment(MainActivity.this);
        LabelPrintedFragment LabelPrintedFragment = new LabelPrintedFragment(MainActivity.this);
        labelcontext=LabelPrintedFragment.huoquconment();
        GPPrinterManager gpPrinterManager = new GPPrinterManager(MainActivity.this);
        AddOperatorFragment addOperatorFragment = new AddOperatorFragment(MainActivity.this);
        ButterKnife.bind(this);
        gpngyongcontext=MainActivity.this;
        gview = (GridView) findViewById(R.id.main_gridview);
        getJsonFromInternet();
        //新建List
        data_list = new ArrayList<Map<String, Object>>();
        //获取数据
        getData();
        //新建适配器
        String[] from = {"image", "text"};
        int[] to = {R.id.gridview_imge, R.id.gridview_text};
        sim_adapter = new SimpleAdapter(this, data_list, R.layout.main_gridview_item, from, to);
        //配置适配器
        gview.setAdapter(sim_adapter);
        gview.setOnItemClickListener(this);
        ButterKnife.bind(this);
        userName.setText(BaseApplication.getAccount().getRealName());
        userDepartment.setText(BaseApplication.getAccount().getDepartmentName());
        num = packageCode(MainActivity.this);

        //动态获取gps权限网络权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.
                    permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.
                    permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.
                    permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.INTERNET);
            }
            if (!permissionList.isEmpty()) {
                String[] permissions = permissionList.toArray(new String[permissionList.size()]);
                ActivityCompat.requestPermissions(this, permissions, 1);
            }
        }

int ves=getVersionCode(MainActivity.this);

        banben.setText("版本号："+getVerName(this));
        new Handler().postDelayed(new Runnable() {
                 @Override
         public void run() {
                     if (Version > ves) {

                         if (isNetworkConnected(MainActivity.this)) {
//                     UpdateConfiguration configuration = new UpdateConfiguration()
//                             //输出错误日志
//                             .setEnableLog(true)
//                             //设置自定义的下载
//                             //.setHttpManager()
//                             //下载完成自动跳动安装页面
//                             .setJumpInstallPage(true)
//                             //设置对话框背景图片 (图片规范参照demo中的示例图)
//                             //.setDialogImage(R.drawable.ic_dialog)
//                             //设置按钮的颜色
//                             //.setDialogButtonColor(Color.parseColor("#E743DA"))
//                             //设置对话框强制更新时进度条和文字的颜色
//                             //.setDialogProgressBarColor(Color.parseColor("#E743DA"))
//                             //设置按钮的文字颜色
//                             .setDialogButtonTextColor(Color.WHITE)
//                             //设置是否显示通知栏进度
//                             .setShowNotification(true)
//                             //设置是否提示后台下载toast
//                             .setShowBgdToast(false)
//                             //设置强制更新
//                             .setForcedUpgrade(false)
//                             //设置对话框按钮的点击监听
//                             .setButtonClickListener(this)
//                             //设置下载过程的监听
//                             .setOnDownloadListener(this);
//
//
                             //简单弹框升级
                             AppDialogConfig config = new AppDialogConfig();
                             config.setTitle("检测到全新版本")
                                     .setOk("升级")
                                     .setContent(apkjieshao)
                                     .setOnClickOk(new View.OnClickListener() {
                                         @Override
                                         public void onClick(View v) {
                                             new AppUpdater.Builder()
                                                     .serUrl(apkUrl)
                                                     .build(MainActivity.this)
                                                     .start();
                                             AppDialog.INSTANCE.dismissDialog();
                                         }
                                     });
                             AppDialog.INSTANCE.showDialog(MainActivity.this, config);

                         } else {
                             Toast.makeText(MainActivity.this, "网络连接失败!", Toast.LENGTH_LONG).show();

                         }
                     } else {
                         if (Version != 0) {
                             Toast.makeText(MainActivity.this, "已经是最新版本!", Toast.LENGTH_LONG).show();


                         }
                     }
                 }
        }, 2000);    //延时1s执行




        }

        /*
         * 整个库允许配置的内容
         * 非必选
         */



    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;

}


    @Override
    protected void onResume() {
        super.onResume();
        marketPresenter.onCreate();
        marketPresenter.BindPresentView(this);
        SimpleRequest simpleRequest = new SimpleRequest();
        simpleRequest.setAccountPkId(BaseApplication.getAccount().getPkId());
        marketPresenter.getTodayResponseInfo(simpleRequest);
    }

//    @OnClick(R2.id.user_icon)   //给 button1 设置一个点击事件
//    public void showToast() {
//
//    }

    public List<Map<String, Object>> getData() {
        //cion和iconName的长度是相同的，这里任选其一都可以
        for (int i = 0; i < icon.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);
            map.put("text", iconName[i]);
            data_list.add(map);
        }

        return data_list;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d("click", position + "");
        switch (position) {
            case 0: {
                Intent intent = new Intent(this, SampleActivity.class);
                startActivity(intent);
            }
            break;
            case 1: {


                Intent intent = new Intent(this, BusinessArchivesActivity.class);
                startActivity(intent);


//                Intent intent=new Intent(this, AddOperatorFragment.class);
//                startActivity(intent);


            }
            break;
            case 2: {
                Intent intent = new Intent(this, SettingActivity.class);
                startActivity(intent);
            }
            break;
            case 3: {
                Intent intent = new Intent(this, NoticeActivity.class);
                startActivity(intent);
            }
            break;
            case 4: {
                Intent intent = new Intent(this, RiskMonitorActivity.class);
                startActivity(intent);
            }
            break;
//            case 2:{
//                }break;
//            case 3:{
//                }break;
        }
        if (position == 1) {

        }
    }

    @Override
    public void onError(String result) {

    }

    @Override
    public void onSuccess(Object resultData) {
        TodayResponseBean todayResponseBean = (TodayResponseBean) resultData;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                samplingCount.setText(todayResponseBean.getSamplingCount() + "批次");
                detectionCount.setText(todayResponseBean.getDetectionCount() + "批次");
                trueDetectionCount.setText(todayResponseBean.getTrueDetectionCount() + "批次");
            }
        });


    }

    public static int packageCode(Context context) {
        PackageManager manager = context.getPackageManager();
        int code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            code = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }

    @Override
    public void start() {

    }

    @Override
    public void downloading(int max, int progress) {

    }

    @Override
    public void done(File apk) {

    }

    @Override
    public void cancel() {

    }

    @Override
    public void error(Exception e) {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onButtonClick(int id) {
        Log.e("TAG", String.valueOf(id));
    }

    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                //mNetworkInfo.isAvailable();
                return true;//有网
            }
        }
        return false;//没有网
    }



    /**
     * 获取网络上的json
     */
    public void getJsonFromInternet () {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpURLConnection conn=(HttpURLConnection) new URL(url).openConnection();
                    conn.setConnectTimeout(3000);
                    conn.setRequestMethod("GET");
                    if (conn.getResponseCode()==200) {
                        InputStream inputStream=conn.getInputStream();
                        listNews=parseJson(inputStream);
                        System.out.println();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    /**
     * 解析json格式的输入流转换成List
     */
    protected UpdateJsonBean parseJson(InputStream inputStream)throws Exception {

        byte[]jsonBytes=convertIsToByteArray(inputStream);
        String json=new String(jsonBytes, "utf-8");
        UpdateJsonBean news=new UpdateJsonBean();
        try {
            JSONObject jsonObject = new JSONObject(json);
            // 返回json的数组

            Version=jsonObject.getInt("version");
            apkUrl=jsonObject.getString("apkUrl");
            apkjieshao=jsonObject.getString("apkjieshao");


            return news;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 将输入流转化成ByteArray
     */
    private byte[] convertIsToByteArray(InputStream inputStream) {
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        byte buffer[]=new byte[1024];
        int length=0;
        try {
            while ((length=inputStream.read(buffer))!=-1) {
                baos.write(buffer, 0, length);
            }
            inputStream.close();
            baos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }

    public int getVersionCode(Context context){

        PackageManager packageManager=context.getPackageManager();

        PackageInfo packageInfo;

        int versionCode=0;

        try {

            packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);

            versionCode=packageInfo.versionCode;

        } catch (PackageManager.NameNotFoundException e) {

            e.printStackTrace();

        }

        return versionCode;

    }




}

